package com.fulihui.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * InetAddress工具类 如获取IP和主机名等
 *
 * @author wang_wx
 * @date 2018-06-12
 */
public class IpAddressUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(IpAddressUtil.class);

    private static final String DEFAULT_LOCAL_IP = "unknown";
    private static final String DEFAULT_LOCAL_HOSTNAME = "unknown";

    /**
     * 获取本机IP
     *
     * @return
     */
    public static String getLocalIp() {
        String ip = DEFAULT_LOCAL_IP;
        InetAddress localInetAddress = getLocalInetAddress();
        if (Objects.nonNull(localInetAddress)) {
            ip = localInetAddress.getHostAddress();
        }
        return ip;
    }

    /**
     * 获取本机IP
     *
     * @return
     */
    public static String getLocalHostName() {
        String hostName = DEFAULT_LOCAL_HOSTNAME;
        InetAddress localInetAddress = getLocalInetAddress();
        if (Objects.nonNull(localInetAddress)) {
            hostName = localInetAddress.getHostName();
        }
        return hostName;
    }

    /**
     * 获取本机InetAddress
     *
     * @return
     */
    public static InetAddress getLocalInetAddress() {
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            LOGGER.error("get InetAddress error={}", e.getMessage(), e);
        }
        return inetAddress;
    }
}
